from django.shortcuts import render,redirect
from rest_framework.views import APIView
import time
from alipay import AliPay

# Create your views here.

def area(request):
    return render(request,'alipay.html')

# 支付宝的接口对象
def ali_pay():
    app_id = '2016101100657333'
     # 默认回调连接
    notify_url = 'http://localhost:8000/area'
    public_key = r'E:\python-work\Cycle-intro\美多商城\md_shop_pro\alipay_app\alipay\public_key.txt'
    private_key = r'E:\python-work\Cycle-intro\美多商城\md_shop_pro\alipay_app\alipay\secrect_key.txt'
    
    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,
        app_private_key_path=private_key, # 私钥文件
        alipay_public_key_path=public_key, # 公钥文件
        # sign_type = 'RAS2',
        # debug=False,
        )
    return alipay

# 通过获取订单信息，提供支付连接
class Pay(APIView):
    def post(self, request):
        price = request.POST.get('price')
        return_url = 'http://localhost:8000/area'
        alipay = ali_pay()
        order_string  = alipay.api_alipay_trade_page_pay(
            # 把参数部分组合成一个连接参数
            subject='美丽商品', # 订单主题
            out_trade_no=str(time.time()), # 订单编号
            total_amount=price,
            return_url=return_url, 
            )
        url = 'https://openapi.alipaydev.com/gateway.do?'     # 支付网关
        print(url+order_string)
        pay_url = url + order_string
        # return render(request,'alipay.html',{'payurl': url + order_string})
        return redirect(pay_url)